<?php

namespace app\admin\controller\user;

use app\admin\model\profession\Profession;
use app\admin\model\user\Vip;
use app\common\controller\Backend;
use app\common\exception\BusinessException;
use app\common\library\Auth;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Exception;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['group', 'profession', 'extend'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 充值会员
     * @return void
     * @throws Exception
     */
    public function recharge($ids)
    {
        // 充值类型:1.会员 2.课程
        $type = $this->request->param('type', 0);
        if (!$type) {
            $this->error(__('充值类型不得为空'));
        }
        if ($this->request->isPost()) {

            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }

            // 提取参数
            $id = $params['id'];
            $course_id = $params['course_id'] ?? 0;
            $profession_id = $params['profession_id'] ?? 0;
            $expire = $params['expire'];
            if (!$id) {
                $this->error(__('会员编号不得为空'));
            }
            if (!$expire) {
                $this->error(__('到期日期不得为空'));
            }
            if ($type == 1) {
                if (!$profession_id) {
                    $this->error(__('请选择充值专业'));
                }
            } else {
                if (!$course_id) {
                    $this->error(__('请选择充值课程'));
                }
            }

            // 检查有效期参数
            $expire_time = strtotime($expire);

            // 循环充值专业
            if ($type == 1) {
                $all_profession_id = explode(', ', $profession_id);
                if (!$all_profession_id) {
                    $this->error(__('未获取到专业信息'));
                }
                foreach ($all_profession_id as $pid) {
                    if ($pid) {
                        try {
                            // 专业充值
                            $model = new \app\admin\model\user\Vip();
                            $model->setExpire($id, $pid, $expire_time);
                        } catch (\Exception $exception) {
                            $this->error($exception->getMessage());
                        }
                    }
                }
            }

            if ($type == 2) {
                $all_course_id = explode(',', $course_id);
                if (!$all_course_id) {
                    $this->error(__('未获取到课程信息'));
                }
                foreach ($all_course_id as $cid) {
                    if ($cid) {
                        try {
                            // 课程充值
                            $model = new \app\admin\model\user\Course();
                            $model->setExpire($id, $cid, $expire_time);
                        } catch (\Exception $exception) {
                            $this->error($exception->getMessage());
                        }
                    }
                }
            }


            $this->success('充值成功');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('type', $type);
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 批量开通会员
     */
    public function batchRechargeVip()
    {
        if ($this->request->isPost()) {
            // 请求参数
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('请求参数不得为空'));
            }
            if (empty($params['attachment'])) {
                $this->error(__('请求文件不得为空'));
            }
            $file = attachmentRealPath($params['attachment']);
            if (!file_exists($file)) {
                $this->error(__('请求文件不存在' . $file));
            }
            try {
                Db::startTrans();
                $this->batchRechargeExecute($file);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->error(__($exception->getMessage()));
            }
            unlink($file);
            $this->success('开通成功');
        }
        return $this->view->fetch();
    }

    /**
     * batchRechargeExecute
     * @return void
     */
    protected function batchRechargeExecute($excelFile)
    {
        // 读取excel
        $spreadsheet = IOFactory::load($excelFile);

        // 转换为数组
        $sheetData = $spreadsheet->getSheet(0)->toArray(null, true, true, true);

        foreach ($sheetData as $key => $item) {
            // 第一行为表头
            if ($key == 1) {
                continue;
            }

            // 提取参数
            $mobile = trim($item['A']);
            $professionId = trim($item['B']);
            $expireDate = trim($item['C']);

            // 检查参数
            try {
                if (empty($mobile) || empty($professionId) || empty($expireDate)) {
                    throw new BusinessException('手机号码或专业编号或开通到期时间值不合法');
                }
            } catch (\Exception $exception) {
                throw new BusinessException('第' . ($key + 1) . '行数据错误:' . $exception->getMessage());
            }

            // 转换有效期
            $expireTime = strtotime($expireDate);
            if (!$expireTime) {
                throw new BusinessException('日期格式不正确');
            }

            // 查询会员信息
            $userModel = new \app\common\model\User();
            $userInfo = $userModel->where(['mobile' => $mobile])->find();
            if (!$userInfo) {
                throw new BusinessException('手机号未注册会员');
            }

            // 查询专业信息
            $professionModel = new Profession();
            $professionModelInfo = $professionModel->find($professionId);
            if (!$professionModelInfo) {
                throw new BusinessException('专业编号不正确');
            }

            // 执行充值
            $userVipModel = new Vip();
            $userVipModel->setExpire($userInfo['id'], $professionId, $expireTime);

        }
    }

}
